
//
//  ZaiXianFuDaoTianJiaXueShengView.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/22.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "ZaiXianFuDaoTianJiaXueShengView.h"
#import "SYRequestAPI+Teach.h"
#import "SYRequestAPI+FuDao.h"
#import "CJClassSelectedView.h"

@interface ZaiXianFuDaoTianJiaXueShengView ()

@property (copy, nonatomic) NSString *templateid;

@property (copy, nonatomic) NSString *url;

@property (copy, nonatomic) NSString *kaoshiType;

@end


@implementation ZaiXianFuDaoTianJiaXueShengView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        [self initSubView];
        [self layout];
    }
    return self;
}
- (void)initSubView{
    _classID = GetDataFromNSUserDefaults(kKaoShiClassId);
    xueHao = @"";
    name = @"";
    self.backgroundColor = [UIColor whiteColor];
    self.xiaoZuChengYuanArray = [NSMutableArray new];
    [self addSubview:self.navView];
    [self addSubview:self.tableView];
    studentArray = [NSMutableArray new];
    //考试 试卷ID 成绩后三名用到
    _templateid = GetDataFromNSUserDefaults(kKaoShiId);
    //选择的辅导类型
    _kaoshiType = GetDataFromNSUserDefaults(kKaoShiType);
    if (_kaoshiType.length > 0) {
        if ([_kaoshiType containsString:@"后三名"]) {
            [self getOrderTopStudent];
            
        } else if ([_kaoshiType containsString:@"成绩异常"]) {
            self.url = @"tutor/TutorClassService.svc/GetOrderChangeAbnormal";
            [self getOrderChangeAbnormal];
            
        } else if ([_kaoshiType containsString:@"出勤异常"]) {
            self.url = @"tutor/TutorClassService.svc/GetAttendAbnormal";
            [self getOrderChangeAbnormal];
            
        }
    } else {
        
    }
    //获得学生列表
    [self getXiaoZuChengYuanRequest];
}
- (void)layout{
    [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@0);
        make.height.equalTo(@44);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(self->_navView.mas_bottom);
        make.bottom.equalTo(@0);
    }];
}
- (ZXFDCCVNav *)navView{
    if (!_navView) {
        ZXFDCCVNav *view = [[ZXFDCCVNav alloc]init];
        view.backgroundColor = MAINBACKCOLOR;
        view.delegate = self;
        view.titleLabe.text = @"创建班级-添加学生";
        [view addSubview:self.complateBtn];
        [_complateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@0).offset(-10);
            make.centerY.equalTo(view.mas_centerY);
            make.width.equalTo(@40);
            make.height.equalTo(@20);
        }];
        [view addSubview:self.banJiButton];
        self.banJiButton.hidden = YES;
        [_banJiButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self->_complateBtn.mas_left).offset(-10);
            make.centerY.equalTo(view.mas_centerY);
            make.width.equalTo(@80);
            make.height.equalTo(@20);
        }];
        _navView = view;
    }
    return _navView;
}
- (void)backClick{
    [UIView animateWithDuration:0.5 animations:^{
        self.frame = CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height);
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
}
- (UIButton *)complateBtn{
    if (!_complateBtn) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"保存" forState:UIControlStateNormal];
        [btn setTitleColor:SELECTEDCOLOR forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn addTarget:self action:@selector(complateClicl:) forControlEvents:UIControlEventTouchUpInside];
        _complateBtn = btn;
    }
    return _complateBtn;
}
- (void)complateClicl:(UIButton *)sender{
    NSString *string = [NSString new];
    NSMutableArray *studentsArr = [NSMutableArray array];
    NSString *className = GetDataFromNSUserDefaults(@"banjiname");
    for (BanJiStudentListModel *model in _xiaoZuChengYuanArray) {
        if (string.length == 0) {
            string = [NSString stringWithFormat:@"%@",model.id];
        }else{
            string = [NSString stringWithFormat:@"%@,%@",string,model.id];
        }
        NSDictionary *dict = @{@"studentId":model.id,
                               @"className":className
                               };
        [studentsArr addObject:dict];
    }
    if (_fdID.length == 0) {
        _fdID = @"1";
    }
    NSDictionary *parama = @{@"id":_fdID,
                             @"students":string};
    [MBProgressHUD mj_showLoading];
    [SYRequestAPI fd_TutorTutorClassStudentAdd:parama success:^(id responseObject) {
        [MBProgressHUD mj_hideHUD];
       // NSLog(@"添加学生 %@",responseObject);
//        NSDictionary *dic = @{@"students":studentsArr,
//                              @"templateCode":@"9"
//                              };
//        [SYRequestAPI postPushFromUrlScheme:@"http://api.31waiyu.com/ParentClientService.svc/External/PushMessage" parameterDict:dic success:^(id responseObject) {
//            [MBProgressHUD mj_hideHUD];
//
//
//        } fail:^(NSError *error) {
//            [MBProgressHUD mj_hideHUD];
//        }];
        [NSObject executeRunloop:^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ZaiXianFuDaoTianJiaXueShengView" object:nil];
        } afterDelay:1.5];
        [XSInfoView showInfo:@"创建班级成功" onView:[UIApplication sharedApplication].keyWindow.rootViewController];
        
    } fail:^(NSError *error) {
        //NSLog(@"请求失败 %@",error);
        [MBProgressHUD mj_hideHUD];
        [XSInfoView showInfo:error.domain onSubView:self];
       // [[NSNotificationCenter defaultCenter]postNotificationName:@"ZaiXianFuDaoTianJiaXueShengView" object:nil];
    }];
}
- (MinButtonViewBtn *)banJiButton{
    if (!_banJiButton) {
        MinButtonViewBtn *btn = [[MinButtonViewBtn alloc]initWithFrame:CGRectMake(90, 12, 69, 20) andType:ButtonImageInRight];
        btn.bottomLabel.text = @"选择班级";
        btn.bottomLabel.font = [UIFont systemFontOfSize:12];
        btn.bottomLabel.textColor = TITLECOLOR;
        btn.topImage.image = [UIImage imageNamed:@"arrow_down"];
        [btn addTarget:self action:@selector(nianjiButton:) forControlEvents:UIControlEventTouchUpInside];
        [btn.bottomLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0).offset(-15);
        }];
        _banJiButton = btn;
    }
    return _banJiButton;
}
- (void)nianjiButton:(MinButtonViewBtn *)sender{
    //选择班级
    __weak typeof(self) mySelf = self;
    [CJClassSelectedView showDatePickerWithTitle:@"选择班级" minDateStr:@"11" resultBlock:^(TeacherClassListModel * _Nonnull selectValue) {
      //  NSLog(@"输出选择的班级 %@",selectValue);
        self->_banJiButton.bottomLabel.text = selectValue.name;
        self->_mainModel = selectValue;
        if (mySelf.classID == self->_mainModel.id) {
            
        }else{
            mySelf.classID = self->_mainModel.id;
            
           [mySelf getXiaoZuChengYuanRequest];
        }
    }];
}
- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, APP_HEIGHT-84) style:UITableViewStylePlain];
        tableView.delegate  =self;
        tableView.dataSource = self;
        tableView.backgroundColor = MAINBACKCOLOR;
        [tableView registerClass:[ZaiXianTianJiaXueShengCell class] forCellReuseIdentifier:@"ZaiXianTianJiaXueShengCellTop"];
        [tableView registerClass:[ZaiXianTianJiaXueShengCell class] forCellReuseIdentifier:@"ZaiXianTianJiaXueShengCellBottom"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    if (_kaoshiType.length > 0) {
//        return 1;
//    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return studentArray.count;
    }
    return _xiaoZuChengYuanArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 100;
    }else{
        return 175;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
       _headerView = [[ZaiXianFuDaoTianJiaXueShengHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width,100)];
        _headerView.titleLabel.text = @"小组成员";
        _headerView.lineViewL.hidden = YES;
        _headerView.lineViewR.hidden = YES;
        [_headerView.titleView reloadView:@[@"学号",@"姓名",@"性别",@"联系人",@"电话",@"状态",@"入学日期",@"移除"]];
    }else{
        _headerView = [[ZaiXianFuDaoTianJiaXueShengHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 175)];
        _headerView.titleLabel.text = @"添加成员";
        _headerView.gongHaoView.hidden = NO;
        _headerView.nameView.hidden = NO;
        _headerView.searchButton.hidden = NO;
        _headerView.lineViewL.hidden = NO;
        _headerView.lineViewR.hidden = NO;
        [_headerView.titleView reloadView:@[@"学号",@"姓名",@"性别",@"联系人",@"电话",@"状态",@"入学日期",@"添加"]];
        _headerView.searchBlock = ^(NSString *searchNameString,NSString *searchGongHaoString){
         //   NSLog(@"搜索字段 %@  %@",searchNameString,searchGongHaoString);
        };
    }
    
    return _headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZaiXianTianJiaXueShengCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZaiXianTianJiaXueShengCellTop" forIndexPath:indexPath];
        
        if (!cell) {
            cell = [[ZaiXianTianJiaXueShengCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ZaiXianTianJiaXueShengCellTop"];
        }
        cell.backgroundColor = MAINBACKCOLOR;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row%2 == 0) {
            cell.backgroundColor = [UIColor whiteColor];
        }else{
            cell.backgroundColor = [UIColorChange colorwithHexString:@"#F8F8F8"];
        }
        [cell.button setBackgroundImage:[UIImage imageNamed:@"fudao_close"] forState:UIControlStateNormal];
        BanJiStudentListModel *mode = _xiaoZuChengYuanArray[indexPath.row];
        NSString *gender;
        if ([mode.sex isEqualToString:@"1"]) {
            gender = @"男";
        }else if ([mode.sex isEqualToString:@"2"]){
            gender = @"女";
        }else{
            gender = @"不确定";
        }
         cell.dataArray = @[mode.serial,mode.name,mode.sex,mode.linker,mode.mobile,mode.statusName,mode.inDate,@""];
        cell.mainModel = mode;
        [cell reloadViewLayout];
        cell.deleteBlock = ^(BanJiStudentListModel * _Nonnull model) {
            [self->_xiaoZuChengYuanArray removeObject:model];
            [self.tableView reloadData];
        };
        cell.block = ^(BanJiStudentListModel * _Nonnull model) {
            [self->_xiaoZuChengYuanArray removeObject:model];
            [self.tableView reloadData];
        };
        return cell;
    }else{
        ZaiXianTianJiaXueShengCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZaiXianTianJiaXueShengCellBottom" forIndexPath:indexPath];
        
        if (!cell) {
            cell = [[ZaiXianTianJiaXueShengCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ZaiXianTianJiaXueShengCellBottom"];
        }
        cell.backgroundColor = MAINBACKCOLOR;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row%2 == 0) {
            cell.backgroundColor = [UIColor whiteColor];
        }else{
            cell.backgroundColor = [UIColorChange colorwithHexString:@"#F8F8F8"];
        }
        BanJiStudentListModel *mode = studentArray[indexPath.row];
        [cell.button setBackgroundImage:[UIImage imageNamed:@"add_teach"] forState:UIControlStateNormal];
        NSString *gender;
        if ([mode.sex isEqualToString:@"1"]) {
            gender = @"男";
        }else if ([mode.sex isEqualToString:@"2"]){
            gender = @"女";
        }else{
            gender = @"不确定";
        }
       
        cell.dataArray = @[mode.serial,mode.name,mode.sex,mode.linker,mode.mobile,mode.statusName,mode.inDate,@""];
        cell.fdID = mode.id;
        cell.mainModel = mode;
        if ([_xiaoZuChengYuanArray containsObject:mode]) {
            cell.button.selected = YES;
        }else{
            cell.button.selected = NO;
        }
        __weak typeof(self)weakSelf = self;
        cell.block = ^(BanJiStudentListModel * _Nonnull model) {
            [weakSelf addtudentReqest:model];
        };
        [cell reloadViewLayout];
        cell.deleteBlock = ^(BanJiStudentListModel * _Nonnull model) {
            [self->_xiaoZuChengYuanArray removeObject:model];
            [self.tableView reloadData];
        };
        return cell;
    }
}
- (UIView *)backV{
    UIView *back = [[UIView alloc]init];
    back.backgroundColor = SELECTEDCOLOR;
    return back;
}


#pragma mark - 得到小组成员
- (void)getXiaoZuChengYuanRequest{
    NSDictionary *parama = @{@"classId":_classID,
                             @"serial":xueHao,
                             @"name":name,
                             @"status":@"",
                             @"tryStatus":@""};
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI sy_getClassServiceClassStudent:parama success:^(id  _Nonnull responseObject) {
      //  NSLog(@"得到小组成员 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            BanJiStudentListModel *model = [[BanJiStudentListModel alloc] init];
            model.id = [dic nilObjectForKey:@"id"];
            model.serial = [dic nilObjectForKey:@"serial"];
            model.name = [dic nilObjectForKey:@"name"];
            if ([dic[@"sex"] isEqualToString:@"1"]) {
                model.sex = @"男";
            }else if ([dic[@"sex"] isEqualToString:@"2"]){
                model.sex = @"女";
            }else{
                model.sex = @"不确定";
            }
            model.headImg = [dic nilObjectForKey:@"headImg"];
            model.father = [dic nilObjectForKey:@"father"];
            model.linker = [dic nilObjectForKey:@"linker"];
            model.mobile = [dic nilObjectForKey:@"mobile"];
            model.status = [dic nilObjectForKey:@"status"];
            model.statusName = [dic nilObjectForKey:@"statusName"];
            model.inDate = [dic nilObjectForKey:@"inDate"];
            model.oper = [dic nilObjectForKey:@"oper"];
            [self->studentArray addObject:model];
        }
        [self.tableView reloadData];
        [MBProgressHUD mj_hideHUDForView:self];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
    }];
}
#pragma mark - 成绩后三名
- (void)getOrderTopStudent {
    NSDictionary *parame = @{@"ClassId":_classID,
                             @"TemplateId":_templateid.length == 0 ?@"":_templateid
                             };
//    [MBProgressHUD mj_showSuccess:nil toView:self];
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI postDataFromURLScheme:@"tutor/TutorClassService.svc/GetOrderTopStudent" parameterDictionary:parame success:^(id responseObject) {
        [MBProgressHUD mj_hideHUDForView:self];
        DeleteDataFromNSUserDefaults(kKaoShiId);
        DeleteDataFromNSUserDefaults(kKaoShiType);
        NSArray *data = responseObject[@"data"];
        for (NSDictionary *dict in data) {
            BanJiStudentListModel *bjModel = [BanJiStudentListModel yy_modelWithDictionary:dict];
            [self->_xiaoZuChengYuanArray addObject:bjModel];
        }
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        DeleteDataFromNSUserDefaults(kKaoShiId);
        DeleteDataFromNSUserDefaults(kKaoShiType);
        [MBProgressHUD mj_hideHUDForView:self];
    }];
}
#pragma mark - 成绩异常
- (void)getOrderChangeAbnormal {
    NSDictionary *parmae = @{@"ClassId":_classID};
    [MBProgressHUD mj_showSuccess:nil toView:self];
    [SYRequestAPI postDataFromURLScheme:_url parameterDictionary:parmae success:^(id responseObject) {
        DeleteDataFromNSUserDefaults(kKaoShiId);
        DeleteDataFromNSUserDefaults(kKaoShiType);
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD mj_hideHUDForView:self];
        NSArray *data = responseObject[@"data"];
        for (NSDictionary *dict in data) {
            BanJiStudentListModel *bjModel = [BanJiStudentListModel yy_modelWithDictionary:dict];
            [self->_xiaoZuChengYuanArray addObject:bjModel];
        }
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        DeleteDataFromNSUserDefaults(kKaoShiId);
        DeleteDataFromNSUserDefaults(kKaoShiType);
        
    }];
}


#pragma mark - 添加学生
- (void)addtudentReqest:(BanJiStudentListModel *)model{
    [self->_xiaoZuChengYuanArray addObject:model];
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
    [self->_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
   
}
@end
